package com.ca.project.core.Respond;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;

import java.io.Serializable;

/**
 * 公共返回对象
 *
 * @PACKAGE_NAME: com.ca.project.core.Respond
 * @NAME: R
 * @USER: ASUS
 * @DATE: 2023/8/25
 * @TIME: 上午 10:38
 **/
// 保证json序列化的时候，如果属性为null，key也一起消失
@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
public class R<T> implements Serializable {
    /**
     * 状态码
     */
    private Integer code;
    /**
     * 状态说明文案
     */
    private String message;
    /**
     * 返回承载
     */
    private T data;

    /**
     * 定义私有构造器
     *
     * @param code
     */
    private R(int code) {
        this.code = code;
    }

    /**
     * 定义私有构造器
     *
     * @param code
     * @param message
     */
    private R(int code, String message) {
        this.code = code;
        this.message = message;
    }

    /**
     * 定义私有构造器
     *
     * @param code
     * @param data
     */
    private R(int code, T data) {
        this.code = code;
        this.data = data;
    }

    /**
     * 定义私有构造器
     *
     * @param code
     * @param message
     * @param data
     */
    private R(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    /**
     * 使其在json序列化的结果当中
     */
    @JsonIgnore
    @JSONField(serialize = false)
    public boolean isSuccess() {
        return code == ResponseCode.SUCCESS.getCode();
    }

    public static <T> R<T> success() {
        return new R<T>(ResponseCode.SUCCESS.getCode());
    }

    public static <T> R<T> success(String message) {
        return new R<T>(ResponseCode.SUCCESS.getCode(), message);
    }

    public static <T> R<T> data(T data) {
        return new R<T>(ResponseCode.SUCCESS.getCode(), data);
    }

    public static <T> R<T> success(String message, T data) {
        return new R<T>(ResponseCode.SUCCESS.getCode(), message, data);
    }

    public static <T> R<T> fail() {
        return new R<T>(ResponseCode.ERROR.getCode(), ResponseCode.ERROR.getDesc());
    }

    public static <T> R<T> fail(String error_message) {
        return new R<T>(ResponseCode.ERROR.getCode(), error_message);
    }

    public static <T> R<T> fail(int error_code, String error_message) {
        return new R<T>(error_code, error_message);
    }

    public static <T> R<T> fail(ResponseCode responseCode) {
        return new R<T>(responseCode.getCode(), responseCode.getDesc());
    }

}
